<script setup lang="ts">
import {onMounted, reactive, ref, watch} from 'vue';
import {useFormRules, useNaiveForm} from '@/hooks/common/form';
import {$t} from '@/locales';
import {fetchGetCurrentTemplates, fetchGetUsers, fetchSaveOrder} from "@/service/api/order";
import {SelectOption} from "naive-ui";
import OrderMember = Api.Entity.OrderMember;

interface Emits {
  (e: 'submitted'): void;
}

defineOptions({
  name: 'AddOrder'
});
const emit = defineEmits<Emits>();
const visible = defineModel<boolean>('visible', {
  default: false
});
const {formRef, validate, restoreValidation} = useNaiveForm();
const {defaultRequiredRule} = useFormRules();
const title = ref('添加订单');
const model: Api.Entity.Order = reactive(createDefaultModel());
const rules: Record<keyof Pick<Api.Entity.Order, 'orderNo'>, App.Global.FormRule> = {
  orderNo: defaultRequiredRule,
};
const templateOptions = ref<SelectOption[]>([]);
const templates = ref<Api.Entity.Template[]>([]);
const currentTemplate = ref<Api.Entity.Template>({
  baseParameter: [],
  body: {},
  name: "",
  role: [],
  isDefault: false,
  company: null
});
const userOptions = ref<SelectOption[]>([]);
function createDefaultModel(): Api.Entity.Order {
  return {
    orderNo: "",
    id: null,
    body: {},
    templateId: null,
    orderMembers: []
  };
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  model.params = {
    orderMembers: model.orderMembers,
    templateId: model.templateId,
  }
  let {error} = await fetchSaveOrder(model);
  if (!error) {
    window.$message?.success($t('common.addSuccess'));
    closeDrawer();
    emit('submitted');
  }
}

async function getCurrentTemplates() {
  let {error, data} = await fetchGetCurrentTemplates();
  if (!error && data) {
    for (let i = 0; i < data?.length; i++) {
      templateOptions.value.push({
        label: data[i].name,
        value: data[i].id || '',
      });
      templates.value.push(data[i]);
    }
  }
}

async function getUsers() {
  let {error, data} = await fetchGetUsers();
  if (!error && data) {
    for (let i = 0; i < data.length; i++) {
      userOptions.value.push({
        label: data[i].nickName,
        value: data[i].id || '',
      })
    }
  }
}

function handleChange(value: number) {
  let a = templates.value.find(item => item.id === value);
  if (a) {
    currentTemplate.value = a;
  }
  model.body = currentTemplate.value.body;

  for (let i = 0; i < currentTemplate.value.role.length; i++) {
    model.orderMembers?.push({
      roleName: "",
      userId: null,
      purview: []
    })

  }
}

async function handleChangeUser(e: any, index: number) {
  if (model.orderMembers === undefined) {
    model.orderMembers = [];
  }
  let roleName = '';
  let purview = [];
  if (currentTemplate.value.role) {
    roleName = currentTemplate.value.role[index].name;
    purview = currentTemplate.value.role[index].columns;
  }
  for (const uid of e) {
    model.orderMembers[index].userId = uid;
    model.orderMembers[index].roleName = roleName;
    model.orderMembers[index].purview = purview;
  }
}

onMounted(() => {

})
watch(visible, () => {
  if (visible.value) {
    getCurrentTemplates();
    getUsers();
    Object.assign(model, createDefaultModel());
    restoreValidation();
  } else {
    templateOptions.value = [];
    model.orderMembers = [];
    templates.value = [];
    userOptions.value = [];
    currentTemplate.value = {
      baseParameter: [],
      body: {},
      name: "",
      role: [],
      isDefault: false,
      company: null
    };
  }
});
</script>
<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="订单编号" path="orderNo">
          <NInput v-model:value="model.orderNo" placeholder=""/>
        </NFormItem>
        <NFormItem label="选择模板" path="templateId">
          <n-select
            v-model:value="model.templateId"
            @update-value="handleChange"
            filterable
            placeholder="选择模板"
            :options="templateOptions"
          />
        </NFormItem>
        <NFormItem v-for="(role,index) in currentTemplate.role" :key="index" :label="role.name" path="">
          <n-select @update:value="handleChangeUser($event,index)" multiple :options="userOptions"/>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
